# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from WebBase import Base

class Upload(Base):

    @view_config(route_name='AppWebUploadIndexRoute', renderer='../../templates/AppWebUploadIndex.pt')
    def AppWebUploadIndexRoute(self):
        tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            portrait = self.request.session['portrait'].replace('/media', '/static')
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait}
        return map

    @view_config(route_name='AppWebUploadRoute', request_method='POST')
    def AppWebUploadRoute(self):
        postParams =  self.request.POST
        #print postParams.getone('image_file')
        #print postParams.getone('image_file').type
        #print postParams.getone('image_file').filename
        #print dir(postParams.getone('image_file').filename)

        #print postParams
        category, name, material, size, weight, aperture, price, description, url ='', '', '', '', '', '', '', '', ''
        try:
            category = postParams.getone('category')
            name = postParams.getone('name')
            material = postParams.getone('material')
            size = postParams.getone('size')
            weight = postParams.getone('weight')
            aperture = postParams.getone('aperture')
            price = postParams.getone('price')
            description = postParams.getone('description')
            url = postParams.getone('url')

            log.debug('[category]' + category)
            log.debug('[name]' + name)
            log.debug('[material]' + material)
            log.debug('[size]' + size)
            log.debug('[weight]' + weight)
            log.debug('[aperture]' + aperture)
            log.debug('[price]' + price)
            log.debug('[description]' + description)
            log.debug('[url]' + url)
            log.debug('[uploadFileList]' + postParams.getall('image_file'))
        except Exception, e:
            log.error(e)

        #file name passed by js
        #uploadName = postParams.getone('image_file').filename
        uploadFileList = postParams.getall('image_file')
        if uploadFileList:
            for uploadFile in uploadFileList:
                uploadName = uploadFile.filename

                #file type, jpg/bmp/gif/png/tiff.etc
                fileType = uploadFile.type
                #this suffix
                suffix = ""
                if fileType == "image/jpeg":
                    suffix = 'jpg'
                elif fileType == "image/bmp":
                    suffix = 'bmp'
                elif fileType == "image/gif":
                    suffix = 'gif'
                elif fileType == "image/png":
                    suffix = 'png'
                elif fileType == "image/tiff":
                    suffix = 'tiff'
                else:
                    suffix = 'ERRORTYPE'

                # The file instance
                input_file = uploadFile.file
                fileMD5 = HashUtil.getFileMD5(input_file.read())
                fileName = fileMD5 + '.' + suffix

                # The file path
                file_path = os.path.join('/media/img', suffix, fileMD5[0: 2], fileMD5[2: 4], fileName)
                temp_file_path = file_path + '.tmp'
                input_file.seek(0)
                folderName = file_path[0: file_path.rfind('/') + 1]
                if not os.path.exists(folderName):
                    os.makedirs(folderName)

                with open(temp_file_path, 'wb') as output_file:
                    shutil.copyfileobj(input_file, output_file)
                os.rename(temp_file_path, file_path)

                thumb_path = os.path.join('/media/thumb', fileMD5[0: 2], fileMD5[2: 4], fileName)
                thumb_path = thumb_path.replace(suffix, 'jpg')
                ImageUtil.make_thumb(file_path, thumb_path, 200, 100)

                #self.request.session['email'] = email
                UploadTasks.uploadImgByQueue(fileMD5, file_path, self.request.session['tel'], category, \
                    name, material, size, weight, aperture, price, description, url)
            return Response("上传成功！")
        else:
            log.error('No....File')
            return Response("上传失败！")
